import { _decorator, Component, Node, Animation, Sprite, resources, SpriteFrame, Vec3, Label } from 'cc';
import { gameEvent, GameEventType, GameStorage, StorageKey } from './Global';
const { ccclass, property } = _decorator;

@ccclass('Settlement')
export class Settlement extends Component {

    @property({ type: Node })
    UseTimeNode: Node = null;
    start() {
        gameEvent.on(GameEventType.GAME_SUCCESS, this.onOver, this);
        gameEvent.on(GameEventType.GAME_TIMER_STOP, this.onOver, this);

        this.restart();
    }

    onDisable() {
        gameEvent.off(GameEventType.GAME_SUCCESS, this.onOver, this);
        gameEvent.off(GameEventType.GAME_TIMER_STOP, this.onOver, this);
    }

    update(deltaTime: number) {

    }

    onOver(state: string) {
        const animation = this.node.getComponent(Animation);
        if (state === GameEventType.GAME_SUCCESS) {
            animation.play('settlement_success_anim')

        }
        if (state === GameEventType.GAME_TIMER_STOP) {
            animation.play('settlement_fail_anim')
        }

    }

    restart() {
        this.node.setWorldPosition(new Vec3(0, -1600, 0))
    }


    // 成功动画调用
    refreshUseTime() {
        const level = GameStorage.getItem(StorageKey.LEVEL) || 1
        const useTimeStr = GameStorage.getItem(StorageKey.GAME_TIME) || '[]'
        try {
            const UseTime = JSON.parse(useTimeStr) || []
            const label = this.UseTimeNode.getComponent(Label);
            label.string = `用时：${(UseTime[level - 1]).toFixed(2)}秒`
        } catch (error) {

        }

    }

}


